# @Time : 2021/8/6 17:16
# @Author : Li Kunlun
# @Description : python符号运算，求解导数微分

import sympy as sp
from sympy import *

# 1、设置变量x,y,z 和函数 f,g
x = sp.Symbol('x')
y, z = sp.symbols('y,z')

f = sp.Function('f')
g = x ** 2 + y ** 2 + z ** 2
"""
输出：
     2    2    2
    x  + y  + z 
"""
sp.pprint(g)

# 2、计算表达式
h = x ** 2 + 2 * x
# 求解结果： 8
print(h.subs(x, 2))

# 3、简化表达式
f = (x ** 2 - x - 6) / (x ** 2 - 3 * x)

"""
(x + 2)/x

x + 2
─────
  x  
"""
print(sp.simplify(f))
sp.pprint(sp.simplify(f))

# 4、展开表达式
f = (x + 1) ** 3 * (x - 2) ** 2
# x**5 - x**4 - 5*x**3 + x**2 + 8*x + 4
print(sp.expand(f))

# 5、合并表达式
f = 3 * x ** 4 - 36 * x ** 3 + 99 * x ** 2 - 6 * x - 144
# 3*(x - 8)*(x - 3)*(x - 2)*(x + 1)
print(sp.factor(f))

# 6、求解计算式微分
y = (sp.sin(x)) ** 2 * sp.exp(2 * x)
z = sp.diff(y, x)
# 2*exp(2*x)*sin(x)**2 + 2*exp(2*x)*sin(x)*cos(x)
print(z)
# 对于导数求解x = 3.2时数值
print(z.subs(x, 3.2))

# 7、求解积分
f = x ** 2 * sp.sin(x ** 2)
g = sp.integrate(f, (x, 0, 5))
# -25*cos(25)*gamma(5/4)/(8*gamma(9/4)) + 5*sqrt(2)*sqrt(pi)*fresnelc(5*sqrt(2)/sqrt(pi))*gamma(5/4)/(16*gamma(9/4))
print(g)

# 8、求解等式解
y = sp.Eq(x ** 3 + 15 * x ** 2, 3 * x - 10)
z = sp.solve(y, x)
print(z)

# 9、求解方程组解
x, y, z = sp.symbols('x,y,z')
eq1 = sp.Eq(x + y + z, 0)
eq2 = sp.Eq(2 * x - y - z, 0)
eq3 = sp.Eq(y + 2 * z, 5)
# {x: 0, y: -5, z: 5}
print(sp.solve([eq1, eq2, eq3], [x, y, z]))
